package com.shitou.shitouproduct.service.impl;

import com.shitou.shitoucommons.utils.RespBean;
import com.shitou.shitouproduct.entity.CarouselEntity;
import org.springframework.stereotype.Service;

import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import com.shitou.shitoucommons.utils.PageUtils;
import com.shitou.shitoucommons.utils.Query;

import com.shitou.shitouproduct.dao.HotSpuDao;
import com.shitou.shitouproduct.entity.HotSpuEntity;
import com.shitou.shitouproduct.service.HotSpuService;

@Transactional
@Service("hotSpuService")
public class HotSpuServiceImpl extends ServiceImpl<HotSpuDao, HotSpuEntity> implements HotSpuService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<HotSpuEntity> page = this.page(
                new Query<HotSpuEntity>().getPage(params),
                new QueryWrapper<HotSpuEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public RespBean getShow() {
        List<HotSpuEntity> list = this.list(new QueryWrapper<HotSpuEntity>().eq("status", 1));

        // TODO 如果获得为空，那么从数据库中寻找一串数据进行展示

        return RespBean.success().put("data", list);
    }

    @Override
    public boolean saveOrUpdateBatch(Collection<HotSpuEntity> entityList) {
        Collection<HotSpuEntity> update = new ArrayList<>();
        Collection<HotSpuEntity> insert = new ArrayList<>();
        List<HotSpuEntity> list = this.list();
        Map<Long, Long> map = new LinkedHashMap<>();
        for (HotSpuEntity hotSpu : list) {
            map.put(hotSpu.getSpuId(), hotSpu.getId());
        }

        Iterator<HotSpuEntity> iterator = entityList.iterator();

        while (iterator.hasNext()) {
            HotSpuEntity hotSpu = iterator.next();
            Long aLong = map.get(hotSpu.getSpuId());
            if ( aLong != null ){
                hotSpu.setId(aLong);
                update.add(hotSpu);
            }else {
                insert.add(hotSpu);
            }
        }
        boolean b = this.updateBatchById(update);
        boolean b1 = this.saveBatch(insert);

        return b && b1;
    }
}
